package com.shiwaixiangcun.customer.module.houserenting

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterRenting
import com.shiwaixiangcun.customer.app.App
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.BannerBean
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.BannerImageLoader
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.activity.*
import com.shiwaixiangcun.customer.utils.*
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import com.shiwaixiangcun.customer.widget.bannerview.Banner
import kotlinx.android.synthetic.main.activity_house_home.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 房屋租售  主页
 * @author Administrator
 */
class HouseRentingMainActivity : BaseActivity(), View.OnClickListener {

    companion object {
        /**
         * 请求数据
         */
        val REQUEST_DATA = 0x0010
        val REQUEST_BANNER = 0x0001
    }

    override fun onClick(p0: View?) {
        val bundle = Bundle()
        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
//          我要出租
            R.id.llayout_lease -> {

                if (LoginHelper.isLogin(mContext)) {
                    val isProperty = AppSharePreferenceMgr.get(App.getContext(), GlobalConfig.propertyAuth, false) as Boolean
                    if (isProperty) {
                        readyGo(ItoRentActivity::class.java)
                    } else {
                        bundle.putString("type", "identification")
                        bundle.putInt("fromActivity", 3)
                        readyGo(ResidentCertificationActivity::class.java, bundle)

                    }
                } else {
                    readyGo(LoginActivity::class.java)
                }

            }
//          我要卖房
            R.id.llayout_sale -> {
                if (LoginHelper.isLogin(mContext)) {
                    val isProperty = AppSharePreferenceMgr.get(App.getContext(), GlobalConfig.propertyAuth, false) as Boolean

                    if (isProperty) {
                        readyGo(ItoSellerActivity::class.java)
                    } else {
                        bundle.putString("type", "identification")
                        readyGo(ResidentCertificationActivity::class.java, bundle)

                    }
                } else {
                    readyGo(LoginActivity::class.java)
                }
            }

//          租房
            R.id.llayout_renting -> {
                bundle.putString("type", "rentHouse")
                readyGo(HouseListActivity::class.java, bundle)
            }

//          二手房
            R.id.llayout_second_hand -> {
                bundle.putString("type", "saleHouse")
                readyGo(HouseListActivity::class.java, bundle)
            }

        }
    }


    private var mLayoutSecondHand: LinearLayout? = null
    private var mLayoutSale: LinearLayout? = null
    private var mLayoutRenting: LinearLayout? = null
    private var mLayoutLease: LinearLayout? = null

    private var mBanner: Banner? = null
    private var viewBanner: View? = null
    private var viewCategory: View? = null
    private var viewTitle: View? = null
    var mHouseList: ArrayList<HouseData>? = null
    var mAdapterRenting: AdapterRenting? = null

    var siteId: Int = 20
    private var pageStart: Int = 1
    var pageSize: Int = 15
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_home)
        EventUtil.getInstance().register(this)
        siteId = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_SITE_ID, 20) as Int
        pageStart = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        initHeaderView()
        initView()

        initData(false)
        initBanner()
    }

    override fun onDestroy() {

        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }

    private fun initBanner() {

        OkGo.get<String>(GlobalApi.getBanner)
                .params("siteId", siteId)
                .params("position", GlobalConfig.house_renting_01)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        Log.e(BUG_TAG, response.toString())
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val jsonString = response?.body()
                        val type = object : TypeToken<ResponseEntity<List<BannerBean>>>() {}.type
                        val responseEntity = JsonUtil.fromJson<ResponseEntity<List<BannerBean>>>(jsonString, type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.RENTING_MAIN, REQUEST_BANNER, responseEntity.data))

                            }
                        }

                    }
                })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updaeUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.RENTING_MAIN) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_BANNER -> {
                val bannerList = simpleEvent.data as List<BannerBean>

                val imageList = bannerList.map { it.imagePath }.toList()

                if (imageList.isEmpty()) {
                    mBanner?.visibility = View.GONE
                } else {
                    mBanner?.visibility = View.VISIBLE
                    mBanner!!.setImages(imageList)
                            .setDelayTime(4000)
                            .start()

                    mBanner?.setOnBannerListener { position ->
                        val bannerBean = bannerList[position]
                        when (bannerBean.bannerType) {
                            "H5" -> {
                                val bundle = Bundle()
                                bundle.putString("h5_url", bannerBean.link as String?)
                                bundle.putString("h5_name", "")
                                if (!bannerBean.link.isNullOrEmpty()) {
                                    readyGo(CommonWebActivity::class.java, bundle)
                                }
                            }
                            else -> {
                                UIClickManager.bannerClick(mContext, bannerBean.link)
                            }

                        }
                    }
                }
            }
            REQUEST_DATA -> {
                val categoryList = simpleEvent.data as HouseList
                mHouseList?.addAll(categoryList.elements)
                mAdapterRenting?.notifyDataSetChanged()
            }
        }
    }

    /**
     * 请求数据
     */
    private fun initData(isLoadMore: Boolean) {
        OkGo.get<String>(GlobalApi.houseRenting)
                .params("page.pn", pageStart)
                .params("page.size", pageSize)
                .params("quality", true)
                .params("siteId", siteId)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        Log.e(BUG_TAG, "error")
                        mAdapterRenting?.setEnableLoadMore(true)
                        mAdapterRenting?.loadMoreFail()
                        refreshLayout.finishRefresh()
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonObjCallBack<HouseList>>() {}.type

                        val responseData = JsonUtil.fromJson<CommonObjCallBack<HouseList>>(response?.body(), type)
                        when (responseData.responseCode) {
                            ResponseConfig.SUCCESS -> {

                                val size = responseData.data.elements.size
                                if (isLoadMore) {
                                    if (size > 0) {

                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.RENTING_MAIN, REQUEST_DATA, responseData.data))

                                    }
                                    if (size == 0 || size < pageSize) {
                                        mAdapterRenting?.loadMoreEnd(false)
                                    } else {
                                        mAdapterRenting?.loadMoreComplete()
                                    }
                                } else {
                                    refreshLayout.finishRefresh()
                                    mAdapterRenting?.setEnableLoadMore(true)
                                    if (size == 0) {
//                                        mClayoutNodata.setVisibility(View.VISIBLE)
                                    } else {
                                        mHouseList?.clear()

                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.RENTING_MAIN, REQUEST_DATA, responseData.data))

                                    }
                                }

                            }
                        }

                    }
                })
    }

    /**
     * 初始化试图
     */
    private fun initView() {

        tv_page_name.text = resources.getText(R.string.house_renting)
        back_left.setOnClickListener(this)
        mHouseList = ArrayList()
        mAdapterRenting = AdapterRenting(mHouseList)
        mAdapterRenting?.addHeaderView(viewBanner)
        mAdapterRenting?.addHeaderView(viewCategory)
        mAdapterRenting?.addHeaderView(viewTitle)
        rv_renting.layoutManager = LinearLayoutManager(this)
        rv_renting.adapter = mAdapterRenting
        val divider = RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setStartSkipCount(1)
                .setEndSkipCount(1)
                .setMarginLeft(20f)
                .setMarginRight(20f)
                .setSize(0.5f)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_renting.addItemDecoration(divider)
        mAdapterRenting?.setOnItemClickListener { adapter, view, position ->
            val houseData = adapter.data[position] as HouseData
            val bundle = Bundle()
            bundle.putLong("houseId", houseData.id)
            bundle.putString("type", houseData.typeValue)
            readyGo(HouseDetailActivity::class.java, bundle)
        }

        mAdapterRenting?.setLoadMoreView(CustomLoadMoreView())

        mAdapterRenting?.setOnLoadMoreListener({
            pageStart += 1
            refreshLayout.finishRefresh()
            initData(true)
        }, rv_renting)

        refreshLayout.setOnRefreshListener {
            pageStart = 1
            mAdapterRenting?.setEnableLoadMore(false)
            initData(false)
        }


    }

    /**
     * 初始化头部
     */
    private fun initHeaderView() {

        viewBanner = layoutInflater.inflate(R.layout.header_banner, null, false)
        viewCategory = layoutInflater.inflate(R.layout.header_renting_category, null, false)
        viewTitle = layoutInflater.inflate(R.layout.header_renting_title, null, false)

        mLayoutSecondHand = viewCategory?.findViewById(R.id.llayout_second_hand)
        mLayoutSale = viewCategory?.findViewById(R.id.llayout_sale)
        mLayoutRenting = viewCategory?.findViewById(R.id.llayout_renting)
        mLayoutLease = viewCategory?.findViewById(R.id.llayout_lease)


        mLayoutSecondHand?.setOnClickListener(this)
        mLayoutSale?.setOnClickListener(this)
        mLayoutRenting?.setOnClickListener(this)
        mLayoutLease?.setOnClickListener(this)

        mBanner = viewBanner?.findViewById(R.id.banner_header)

        val widthPx = ScreenUtil.getScreenWidth(this)
        val paddingPx = DisplayUtil.dip2px(this, 40f)

        val bannerHeight = (widthPx - paddingPx) / 3
        val layoutParams = mBanner?.layoutParams
        layoutParams?.height = bannerHeight
        mBanner?.layoutParams = layoutParams
        mBanner?.setImageLoader(BannerImageLoader())

//        Log.e(BUG_TAG, widthDp as String)
    }
}
